package demo.spring.restful.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.stereotype.Component;

import demo.spring.restful.domain.Computer;

@Component
public class ComputerService {
	
		private static final AtomicLong counter = new AtomicLong();
	    
	    private static List<Computer> computers;
	     
	    static{
	        computers= populateDummyComputers();
	    }
	 
	    public List<Computer> findAllComputer() {
	        return computers;
	    }
	     
	    public Computer findById(long id) {
	        for(Computer computer:computers){
	            if(computer.getId() == id){
	                return computer;
	            }
	        }
	        return null;
	    }
	     
	    public Computer findByBrand(String brand) {
	        for(Computer computer:computers){
	            if(computer.getBrand().equalsIgnoreCase(brand)){
	                return computer;
	            }
	        }
	        return null;
	    }
	     
	    public void saveComputer(Computer computer) {
	        computer.setId(counter.incrementAndGet());
	        computers.add(computer);
	    }
	 
	    public void updateComputer(Computer computer) {
	        int index = computers.indexOf(computer);
	        computers.set(index, computer);
	    }
	 
	    public void deleteComputerById(long id) {
	         
	        for (Iterator<Computer> iterator = computers.iterator(); iterator.hasNext(); ) {
	        	Computer computer = iterator.next();
	            if (computer.getId() == id) {
	                iterator.remove();
	            }
	        }
	    }
	 
	    public boolean isComputerExist(Computer computer) {
	        return findByBrand(computer.getBrand())!=null;
	    }
	 
	    private static List<Computer> populateDummyComputers(){
	        List<Computer> computers = new ArrayList<Computer>();
	        computers.add(new Computer(counter.incrementAndGet(),"hp","2.3G"));
	        computers.add(new Computer(counter.incrementAndGet(),"lenove","2.4G"));
	        computers.add(new Computer(counter.incrementAndGet(),"Dell","2.5G"));
	        computers.add(new Computer(counter.incrementAndGet(),"Apple","2.1G"));
	        return computers;
	    }
	 
	    public void deleteAllComputers() {
	    	 computers.clear();
	    }
	
}
